package site.xuxingcan.tvlauncher;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;

/**
 * Created by xuxingcan on 2016/7/28.
 */
public class FileUtil {
    private Gson gson;
    private ArrayList<MessageModel> messageModelArrayList;
    private SharedPreferences mSharedPreferences;
    private static volatile FileUtil instance = null;

    public static FileUtil getInstance(Context context) {
        if (instance == null) {
            synchronized (FileUtil.class) {
                if (instance == null) {
                    instance = new FileUtil(context);
                }
            }
        }
        return instance;
    }

    public ArrayList<MessageModel> getMessageModelArrayList() {
        return messageModelArrayList;
    }

    private FileUtil(Context context) {
        gson = new Gson();
        mSharedPreferences = context.getSharedPreferences("default", Context.MODE_PRIVATE);
        try {
            messageModelArrayList = gson.fromJson(getUserData(),
                    new TypeToken<ArrayList<MessageModel>>() {
                    }.getType());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (messageModelArrayList == null) {
            messageModelArrayList = new ArrayList<>();
        }
    }

    public void addMessage(MessageModel messageModel) {
        messageModelArrayList.add(0, messageModel);
        while (messageModelArrayList.size() > 500) {
            messageModelArrayList.remove(messageModelArrayList.size() - 1);
        }
        setUserData(gson.toJson(messageModelArrayList));
    }

    private String getUserData() {
        return mSharedPreferences.getString("user_data", null);
    }

    private void setUserData(String s) {
        mSharedPreferences.edit().putString("user_data", s).apply();
    }
}
